<?php

use Biz\model\GoodsTestActivity\FineGoodsContentModel;
use Biz\model\store\StoreBasic as mStoreBasic;
use Biz\model\wiki\Wiki as mWiki;
use Biz\service\brand\Brand as sBrand;
use Biz\service\wiki\Wiki as sWiki;
use Biz\service\wiki\WikiContent;
use Doraemon\model\AdmUserType;
use Doraemon\pockets\constInterface\FormatScene;
use Doraemon\model\Elasticsearch\EsObjRelateWikiModel;
use Doraemon\service\es\EsObjRelateWikiSupplement;
use Doraemon\service\Format\FormatMix;
use Doraemon\service\statSign\Basic as basicStatSign;
use Doraemon\tools\ActionLog;
use Doraemon\tools\BlockType;
use Doraemon\tools\IdParse;

/**
 * wiki详情页下面的  住友说、品牌说、门店说、测评报告、全部
 */
class getWikiRelaCommunitAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_NOTHING;

    const PAGE_SIZE = 10;

    const USER_COMMENT = 0;//住友说
    const BRAND_COMMENT = 1;//品牌说
    const STORE_COMMENT = 2;//门店说
    const TEST_REPORT_COMMENT = 3;//测评报告
    const ALL_COMMENT = 4;//全部


    private int $logType = 0;//0：住友说 1：品牌说
    private int $basicId = 0;
    private array $wikiIds = [];
    private int $isOver = 0;
    private int $total = 0;
    private int $wikiBrandId = 0;
    private int $wikiStoreId = 0;
    private int $actFrom = 0;


    public function main()
    {
        $wiki_id = $this->getRequest()->getPost('wiki_id', '25'); //测试数据dev: 25 ,test:7387
        $page = $this->getRequest()->getPost('page', 1);
//        $pageSize = $this->getRequest()->getPost('page_size', self::PAGE_SIZE);
        $pageSize = self::PAGE_SIZE;
        $type = $this->getRequest()->getPost('type', 0); //0：住友说、1：品牌说、 2：门店说、 3：测评报告、4：全部
        //中间页：1,找好物：2 ，详情页:3
        $act_from = (int)$this->getRequest()->getPost('act_from', 3);
        $this->actFrom = $act_from;
        $this->logType = $type;
        $actionType = $this->getActionType();
        $spuInfo = sWiki::getWikiBaseInfos([$wiki_id]);
        $spuInfo = ($spuInfo && isset($spuInfo[$wiki_id])) ? $spuInfo[$wiki_id] : [];
        $basicId = $spuInfo ? $spuInfo['basic_id'] : 0;

        $this->basicId = $basicId;
        $this->wikiBrandId = $spuInfo['brand_id'] ?? 0;
        $this->wikiStoreId = $spuInfo['store_id'] ?? 0;
        $this->wikiIds = [$wiki_id];
        if ($this->wikiBrandId && $this->basicId) {
            $wikiIds = mWiki::selectByWhere([
                'basic_id' => $this->basicId,
                'status[!]' => mWiki::STATUS_DEL,
            ], 'id');
            $this->wikiIds = array_merge([$wiki_id], $wikiIds);
        }
        ActionLog::log($this->uid, ['wikiID' => $basicId ? $basicId : 0, 'page' => $page, 'action_from' => $act_from],
            $actionType);
        $obj_ids = [];
        switch ($type) {
            case self::ALL_COMMENT;
                // 全部
                $obj_ids = $this->getAllComment($page, $pageSize);
                break;
            case self::USER_COMMENT;
                // 住友说
                $obj_ids = $this->getUserComment($page, $pageSize);
                break;
            case self::BRAND_COMMENT;
                // 品牌说
                $obj_ids = $this->getBrandComment($page, $pageSize);
                break;
            case self::STORE_COMMENT;
                // 门店说
                $obj_ids = $this->getStoreComment($page, $pageSize);
                break;
            case self::TEST_REPORT_COMMENT;
                // 测评报告
                $obj_ids = $this->getTestReportComment($page, $pageSize);
                break;
        }
        $list = $this->formatData($obj_ids);
        $this->setSuccess(['list' => $list, 'is_over' => $this->isOver, 'count' => $this->total]);
    }

    private function getActionType()
    {
        $result = ActionLog::BIZ_WIKI_DETAIL_RELATE_CONTENT;
        switch ($this->logType) {
            case 0:
                $result = ActionLog::BIZ_WIKI_DETAIL_RELATE_CONTENT;
                break;
            case 1:
                $result = ActionLog::BIZ_WIKI_DETAIL_BRAND_INFO;
                break;
            case 2:
                $result = ActionLog::BIZ_WIKI_DETAIL_STORE_INFO;
                break;
        }

        return $result;
    }

    /**
     * @param $page
     * @param $pageSize
     * @return array
     */
    private function getAllComment($page, $pageSize): array
    {
        //先根据内容类型排序（测评报告内容>精选内容>优质内容>普通内容），再加时间倒序
        $allTestReportObjIds = $this->getTestReportComment(1, 100);//目前测评报告数量最多为15条 这里要取全部测评报告 和住友说进行去重处理
//        $allObjIds = EsObjRelateWikiSupplement::search([
//            'wiki_id_arr' => $this->wikiIds,
//            'page' => 1, // 由于是取全量数据 这里固定写1
//            'pagesize' => 9999,
//        ]);
        $allObjIds = EsObjRelateWikiModel::search([
            'wiki_id_arr' => $this->wikiIds,
        ],1,9999);
        $allObjIds = array_column($allObjIds['rows'], 'obj_id');
        if($allObjIds){
            $allObjIds =  array_diff($allObjIds, $allTestReportObjIds);
        }
        $objIds = array_merge($allTestReportObjIds,$allObjIds);
        $this->total = count($objIds);
        $start_id = ($page - 1) * $pageSize;
        $is_over = (($start_id + $pageSize) >= $this->total) ? 1 : 0;
        $this->isOver = $is_over;
        return array_slice($objIds,$start_id,$pageSize);

    }

    /**
     * @param $page
     * @param $pageSize
     * @return array
     * @throws \Exception
     */
    private function getTestReportComment($page, $pageSize): array
    {
        $objIds = [];
        $start_id = ($page - 1) * $pageSize;
        if ($this->basicId) {
            $objIds = FineGoodsContentModel::all([
                'basic_id' => $this->basicId,
                'is_delete[!]' => FineGoodsContentModel::IS_DELETE_TRUE,
                'ORDER' => ['points' => 'DESC', 'addtime' => 'DESC'],
            ], 'obj_id');
            if ($objIds) {
//                $data = EsObjRelateWikiSupplement::search([
//                    'obj_id_arr' => $objIds,
//                    'wiki_id_arr' => $this->wikiIds,
//                    'pagesize' => $pageSize,
//                    'is_test' => 1,//0 表示普通内容 1表示测评报告
//                ]);
                $data = EsObjRelateWikiModel::search([
                    'obj_id_arr' => $objIds,
                    'wiki_id_arr' => $this->wikiIds,
                    'is_test' => 1,//0 表示普通内容 1表示测评报告
                ],1,$pageSize);
                $objIds = array_column($data['rows'], 'obj_id');
                $this->total = count($objIds);
                $objIds = array_slice($objIds,$start_id,$pageSize);
            }
        }
        $is_over = (($start_id + $pageSize) >= $this->total) ? 1 : 0;
        $this->isOver = $is_over;
        return $objIds;
    }

    /**
     * @param $page
     * @param $pageSize
     * @return array
     * @throws \Exception
     */
    private function getUserComment($page, $pageSize): array
    {
        if ($this->wikiBrandId) {
            $brandInfo = sBrand::getBrandsInfoByIds([$this->wikiBrandId]);
            if ($brandInfo && isset($brandInfo[$this->wikiBrandId]) && $brandInfo[$this->wikiBrandId]['uid']) {
                $brandUid = $brandInfo[$this->wikiBrandId]['uid'];
            }
        } else {
            if ($this->wikiStoreId) {
                $storeInfo = mStoreBasic::getStoreInfoById($this->wikiStoreId);
                $storeUid = !empty($storeInfo) ? $storeInfo['uid'] : 0;
            }
        }
        $filterUid[] = $brandUid ?? 0;
        $filterUid[] = $storeUid ?? 0;
        $filterUid = array_values(array_filter($filterUid));
//        $data = EsObjRelateWikiSupplement::search([
//            'wiki_id_arr' => $this->wikiIds,
//            'filter_uid_arr' => $filterUid,
//            'pagesize' => $pageSize,
//            'page' => $page,
//        ]);
        $data = EsObjRelateWikiModel::search([
            'wiki_id_arr' => $this->wikiIds,
            'filter_uid_arr' => $filterUid,
        ],$page,$pageSize);
        $this->total = $data['total'];
        $start_id = ($page - 1) * $pageSize;
        $is_over = (($start_id + $pageSize) >= $this->total) ? 1 : 0;
        $this->isOver = $is_over;

        return array_column($data['rows'], 'obj_id');
    }

    private function getBrandComment($page, $pageSize): array
    {
        $objIds = [];
        $brandUid = 0;
        if ($this->wikiBrandId) {
            $brandInfo = sBrand::getBrandsInfoByIds([$this->wikiBrandId]);
            if ($brandInfo && isset($brandInfo[$this->wikiBrandId]) && $brandInfo[$this->wikiBrandId]['uid']) {
                $brandUid = $brandInfo[$this->wikiBrandId]['uid'];
            }
//            $data = EsObjRelateWikiSupplement::search([
//                'wiki_id_arr' => $this->wikiIds,
//                'uid' => $brandUid,
//                'pagesize' => $pageSize,
//                'page' => $page,
//            ]);
            $data = EsObjRelateWikiModel::search([
                'wiki_id_arr' => $this->wikiIds,
                'uid' => $brandUid,
            ],$page,$pageSize);
            $this->total = $data['total'];
            $start_id = ($page - 1) * $pageSize;
            $is_over = (($start_id + $pageSize) >= $this->total) ? 1 : 0;
            $this->isOver = $is_over;
            $objIds = array_column($data['rows'], 'obj_id');
        }

        return $objIds;
    }

    private function getStoreComment($page, $pageSize): array
    {
        $objIds = [];
        if ($this->wikiStoreId) {
            $storeInfo = mStoreBasic::getStoreInfoById($this->wikiStoreId);
            $storeUid = !empty($storeInfo) ? $storeInfo['uid'] : 0;
//            $data = EsObjRelateWikiSupplement::search([
//                'wiki_id_arr' => $this->wikiIds,
//                'uid' => $storeUid,
//                'pagesize' => $pageSize,
//                'page' => $page,
//            ]);
            $data = EsObjRelateWikiModel::search([
                'wiki_id_arr' => $this->wikiIds,
                'uid' => $storeUid,
            ],$page,$pageSize);
            $this->total = $data['total'];
            $start_id = ($page - 1) * $pageSize;
            $is_over = (($start_id + $pageSize) >= $this->total) ? 1 : 0;
            $this->isOver = $is_over;
            $objIds = array_column($data['rows'], 'obj_id');
        }

        return $objIds;
    }

    /**
     * @param $obj_ids
     * @return array
     */
    private function formatData($obj_ids): array
    {
        $list = [];
        if ($obj_ids) {
            $obj_info = [];
            foreach ($obj_ids as $k => $obj_id) {
                if (!$obj_id) {
                    continue;
                }
                $obj_info[$k]['obj_id'] = $obj_id;
                $obj_info[$k]['obj_type'] = IdParse::getType($obj_id);
            }
            $obj_infos = FormatMix::format($obj_info, $this->uid, FormatScene::TALK_ABOUT_INFO) ?: [];
            $blank_list_map = $this->getBlankListMap($obj_infos[BlockType::TYPE_BLANK] ?? []) ?: [];
            $article_list_map = $this->getArticleListMap($obj_infos[BlockType::TYPE_ARTICLE] ?? []) ?: [];
            $guide_list_map = $this->getGuideListMap($obj_infos[BlockType::TYPE_GUIDE] ?? []) ?: [];
            $note_list_map = $this->getNoteListMap($obj_infos[BlockType::TYPE_PHOTO] ?? []) ?: [];

            foreach ($obj_ids as $obj_id) {
                $objType = IdParse::getType($obj_id);
                switch ($objType) {
                    case BlockType::TYPE_PHOTO:
                    case BlockType::TYPE_ANSWER:
                        if (isset($note_list_map[$obj_id]) && $note_list_map[$obj_id]) {
                            $list[] = $note_list_map[$obj_id];
                        }
                        break;
                    case BlockType::TYPE_ARTICLE:
                        if (isset($article_list_map[$obj_id]) && $article_list_map[$obj_id]) {
                            $list[] = $article_list_map[$obj_id];
                        }
                        break;
                    case BlockType::TYPE_BLANK:
                        if (isset($blank_list_map[$obj_id]) && $blank_list_map[$obj_id]) {
                            $list[] = $blank_list_map[$obj_id];
                        }
                        break;
                    case BlockType::TYPE_GUIDE:
                        if (isset($guide_list_map[$obj_id]) && $guide_list_map[$obj_id]) {
                            $list[] = $guide_list_map[$obj_id];
                        }
                        break;
                }
            }
        }

        return $list;
    }

    /**
     * 文章列表
     * @param array $blank_lists
     * @return array
     */
    private function getBlankListMap(array $blank_lists): array
    {
        if (!$blank_lists) {
            return [];
        }
        $uids = array_map([new IdParse(), 'getUid'], array_keys($blank_lists));
        $black_uids = AdmUserType::isBlevelMulti($uids);//B级
        $filter_uids = array_merge($black_uids, WikiContent::FILTER_UIDS);
        foreach ($blank_lists as $obj_id => $blank) {
            $uid = IdParse::getUid($obj_id);
            if (in_array($uid, $filter_uids)) {
                unset($blank_lists[$obj_id]);
                continue;
            }
            $wiki_list = $blank['blank']['wiki_info']['list'] ?? [];
            if ($wiki_list) {
                $blank_lists[$obj_id]['blank']['wiki_info']['list'] = $this->_setStatSignForWiki($wiki_list);
            }
        }

        return $this->_setStatSign($blank_lists, BlockType::TYPE_BLANK);
    }

    /**
     * 增加wiki列表埋点
     * @param array $lists
     * @return array
     */
    private function _setStatSignForWiki(array $lists): array
    {
        if (!$lists) {
            return [];
        }
        foreach ($lists as &$info) {
            $info['statSign'] = basicStatSign::genStatSign(basicStatSign::MODULE_TODAY_NGT_WIKI_LIST, [
                basicStatSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI,
                basicStatSign::EXTEND_KEY_OBJ_ID => $info['wiki_id'],
            ], [
                'wiki_id' => $info['wiki_id'],
                'basic_id' => $info['basic_id'],
                'uid' => $this->uid,
                'act_from' => $this->actFrom,
            ]);
        }

        $lists = \Doraemon\tools\StatSign::versionCompatible($lists, \Doraemon\tools\StatSign::WIKI_UP_GRADE_VERSION_522, \Doraemon\tools\BlockType::TYPE_WIKI, 'wiki' );
        return $lists;
    }

    /**
     * 增加内容statSign
     * @param array $lists
     * @param $type
     * @return array
     */
    private function _setStatSign(array $lists, $type): array
    {
        if (!$lists) {
            return [];
        }
        foreach ($lists as $obj_id => &$list) {
            $list['statSign'] = basicStatSign::genStatSign($this->getStatSignType(), [
                basicStatSign::EXTEND_KEY_OBJ_ID => $obj_id,
                basicStatSign::EXTEND_KEY_OBJ_TYPE => $type,
            ], ['wiki_id' => $this->basicId]);
        }

        return $lists;
    }

    private function getStatSignType()
    {
        $result = '';
        switch ($this->logType) {
            case 0:
                $result = basicStatSign::MODULE_WIKI_DETAIL_USER_CONTENT;
                break;
            case 1:
                $result = basicStatSign::MODULE_WIKI_DETAIL_BRAND_CONTENT;
                break;
            case 2:
                $result = '';//todo 添加statSign
                break;
        }

        return $result;
    }

    /**
     * 获取文章
     * @param array $article_lists
     * @return array
     */
    private function getArticleListMap(array $article_lists): array
    {
        $uids = array_map([new IdParse(), 'getUid'], array_keys($article_lists));
        $black_uids = AdmUserType::isBlevelMulti($uids);//B级
        $filter_uids = array_merge($black_uids, WikiContent::FILTER_UIDS);
        if ($article_lists && is_array($article_lists)) {
            foreach ($article_lists as $obj_id => &$article) {
                $uid = IdParse::getUid($obj_id);
                if (in_array($uid, $filter_uids)) {
                    unset($article_lists[$obj_id]);
                }
            }
        }

        return $this->_setStatSign($article_lists, BlockType::TYPE_ARTICLE);
    }

    /**
     * 获取指南
     * @param $guide_lists
     * @return array
     */
    private function getGuideListMap($guide_lists): array
    {
        if (!$guide_lists) {
            return [];
        }
        $uids = array_map([new IdParse(), 'getUid'], array_keys($guide_lists));
        $black_uids = AdmUserType::isBlevelMulti($uids);//B级
        $filter_uids = array_merge($black_uids, WikiContent::FILTER_UIDS);
        foreach ($guide_lists as $obj_id => $guide) {
            $uid = IdParse::getUid($obj_id);
            if (in_array($uid, $filter_uids)) {
                unset($guide_lists[$obj_id]);
                continue;
            }
            $wiki_list = $guide_lists['guide']['wiki_info']['list'] ?? [];
            if ($wiki_list) {
                $guide_lists[$obj_id]['guide']['wiki_info']['list'] = $this->_setStatSignForWiki($wiki_list);
            }
        }

        return $this->_setStatSign($guide_lists, BlockType::TYPE_GUIDE);
    }

    /**
     * 获取note
     * @param $note_lists
     * @return array
     */
    private function getNoteListMap($note_lists): array
    {
        if (!$note_lists) {
            return [];
        }
        $uids = array_map([new IdParse(), 'getUid'], array_keys($note_lists));
        $black_uids = AdmUserType::isBlevelMulti($uids);//B级
        $filter_uids = array_merge($black_uids, WikiContent::FILTER_UIDS);
        foreach ($note_lists as $obj_id => $note_list) {
            $note_uid = IdParse::getUid($obj_id);
            if (in_array($note_uid, $filter_uids)) {
                unset($note_lists[$obj_id]);
                continue;
            }
            $wiki_list = $note_list['photo']['wiki_info']['list'] ?? [];
            if ($wiki_list) {
                $note_lists[$obj_id]['photo']['wiki_info']['list'] = $this->_setStatSignForWiki($wiki_list);
            }
        }

        return $this->_setStatSign($note_lists, BlockType::TYPE_PHOTO);

    }

}
